package com.it.server.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.it.common.context.BaseContext;
import com.it.common.exception.OrderBusinessException;
import com.it.common.result.PageResult;
import com.it.common.result.Result;
import com.it.common.utils.WeChatPayUtil;
import com.it.pojo.DTO.OrderDTO;
import com.it.pojo.DTO.OrderPaymentDTO;
import com.it.pojo.DTO.OrdersPageQueryDTO;
import com.it.pojo.Entity.*;
import com.it.pojo.VO.CartItemVO;
import com.it.pojo.VO.OrderPaymentVO;
import com.it.pojo.VO.OrderSubmitVO;
import com.it.pojo.VO.OrdersVO;
import com.it.server.mapper.*;
import com.it.server.service.OrderService;
import com.it.server.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartItemMapper cartItemMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderDishMapper oderDishMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Override
    @Transactional
    public OrderSubmitVO submit(OrderDTO orderDTO) {
        Integer userId = BaseContext.getCurrentId().intValue();
        Address address = addressMapper.selectById(orderDTO.getAddressId());
        CartItem cartItem =new CartItem();
        cartItem.setUserId(userId);
        cartItem.setMerchantId(orderDTO.getMerchantId());
        List<CartItemVO> cartItemList = cartItemMapper.list(cartItem);
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderDTO, orders);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setAddress(address.getDetail());
        orders.setConsignee(address.getConsignee());
        orders.setPhone(address.getPhone());

        orderMapper.insert(orders);


        List<OrdersDish> ordersDishList =new ArrayList<>();
        for(CartItemVO cartItemVO:cartItemList){
            OrdersDish ordersDish = new OrdersDish();
            BeanUtils.copyProperties(cartItemVO, ordersDish);
            ordersDish.setImage(cartItemVO.getImage_url());
            ordersDish.setOrderId(orders.getId());
            ordersDishList.add(ordersDish);
        }

        oderDishMapper.insertBatch(ordersDishList);

        cartItemMapper.clear(userId,orders.getMerchantId());

        OrderSubmitVO orderSubmitVO =OrderSubmitVO.builder()
                .id(orders.getId())
                .number(orders.getNumber())
                .amount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    @Override
    public OrderPaymentVO payment(OrderPaymentDTO orderPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        Users user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                orderPaymentDTO.getNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "极创外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }
    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type",1); // 1表示来单提醒 2表示客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号：" + outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public void cancel(Integer id) throws Exception {
    Orders ordersDB =orderMapper.getById(id);
    if (ordersDB == null){
        throw new RuntimeException("订单不存在");
    }
    if(ordersDB.getStatus()>2){
        throw new RuntimeException("订单状态有误");
    }
    Orders orders = new Orders();
    orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);


    }

    @Override
    public PageResult pageQuery(int page, int pageSize, Integer status) {
        PageHelper.startPage(page,pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        Page<Orders> pageQuery = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrdersVO> list = new ArrayList();
        if(pageQuery!=null&&pageQuery.getTotal()>0){
            for(Orders orders : pageQuery){
            Integer id = orders.getId();
            List<OrdersDish> ordersDishList = oderDishMapper.getByOrderId(id);
            OrdersVO ordersVO = new OrdersVO();
            BeanUtils.copyProperties(orders,ordersVO);
            ordersVO.setOrdersDishes(ordersDishList);
            list.add(ordersVO);
            }

        }

        return new PageResult(pageQuery.getTotal(), list);
    }


    public OrdersVO getOrderDetail(Integer id) {
        Orders orders = orderMapper.getById(id);
        List<OrdersDish> ordersDishList = oderDishMapper.getByOrderId(orders.getId());
        OrdersVO ordersVO = new OrdersVO();
        BeanUtils.copyProperties(orders,ordersVO);
        ordersVO.setOrdersDishes(ordersDishList);
        return ordersVO;
    }

}
